package ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.DefaultTableModel;

import controller.CityController;
import controller.CountryController;
import controller.OutsiderController;
import controller.SubContractorController;
import model.City;
import model.Country;
import model.SubContractor;
import model.SubContractorJob;
import util.ImagePanel;
import util.EmailValidator;
import util.Menu;
import util.PdfFilePrint;

public class SubContractorUI implements ActionListener, ListSelectionListener 
{
	private boolean startup = false;

	private static SubContractorUI instance = null;

	private SubContractorController subContractorCtrl;
	private CountryController countryCtrl;
	private CityController cityCtrl;
	private OutsiderController outsiderCtrl;

	private EmailValidator emailValidator;

	private JFrame frameSubContractorUI;

	private JTabbedPane tabbedPane;

	private JPanel redPanel;

	private Image image = null;

	private ImagePanel newSubContractor;
	private ImagePanel allSubContractors;
	private ImagePanel jobsSubContractor;

	private JTable allSubContractorsTable;
	private DefaultTableModel allSubContractorsTableModel;

	private JList<String> jobsSubContractorEditListJobs;
	private DefaultListModel<String> jobsSubContractorEditListJobsModel;

	private JComboBox<String> allSubContractorsComboBoxSearchJobs;
	private JComboBox<String> allSubContractorsComboBoxSearchType;
	private JComboBox<String> newSubContractorComboBoxStatus;
	private JComboBox<String> newSubContractorComboBoxCountry;
	private JComboBox<String> newSubContractorComboBoxCity;
	private	JComboBox<String> newSubContractorComboBoxJob;
	private JComboBox<String> editSubContractorComboBoxCountry;
	private JComboBox<String> editSubContractorComboBoxCity;
	private JComboBox<String> editSubContractorComboBoxJob;

	private JButton newSubContractorButtonCreateSubContractor;
	private JButton allSubContractorsButtonSearchClear;
	private JButton allSubContractorsButtonEditSubContractor;
	private JButton allSubContractorsButtonDeactivateSubContractor;
	private JButton jobsSubContractorNewButtonJobAdd;
	private JButton jobsSubContractorEditButtonJobEdit;
	private JButton statistics;

	private JCheckBox allSubContractorsCheckBoxOnlyActiveSubContractors;

	private JTextField allSubContractorsTextFieldSearchFor;
	private JTextField newSubContractorTextFieldUsername;
	private JTextField newSubContractorTextFieldPhoneNo;
	private JTextField newSubContractorTextFieldEmail;
	private JTextField jobsSubContractorNewTextFieldJobName;
	private JTextField jobsSubContractorEditTextFieldJobName;
	private JTextField jobsSubContractorEditTextFieldJobCount;

	private JScrollPane jobsSubContractorEditListScrollPane;

	private JMenuBar menu;

	private Menu menuBar;

	private ArrayList<JTextField> newSubContractorTextFields;
	private ArrayList<JTextField> editSubContractorTextFields;

	private ArrayList<SubContractorJob> subContractorJobList;

	private backButton back;
	private JButton btnBack;
	private JButton btnPrint;

	public void display()
	{
		frameSubContractorUI.getContentPane().add(redPanel);

		redPanel.add(tabbedPane);


		tabbedPane.add("All SubContractors", allSubContractors);
		tabbedPane.add("New SubContractor", newSubContractor);
		tabbedPane.add("SubContractor Jobs", jobsSubContractor);

		frameSubContractorUI.setSize(800,420);
		frameSubContractorUI.setLocationRelativeTo(null);
		frameSubContractorUI.setVisible(true);
		frameSubContractorUI.setResizable(false);
	}

	public SubContractorUI()
	{
		frameSubContractorUI = new JFrame("SubContractor UI");

		back = new backButton();
		back.setNumber("8");

		menuBar = Menu.getInstance();

		menu = menuBar.makeJMenuBar();

		frameSubContractorUI.setJMenuBar(menu);

		redPanel = new JPanel();
		redPanel.setBackground(new Color(165, 42, 42));

		tabbedPane = new JTabbedPane();
		tabbedPane.setBounds(0, 34, 794, 309);

		cityCtrl = new CityController();
		countryCtrl = new CountryController();
		subContractorCtrl = new SubContractorController();
		outsiderCtrl = new OutsiderController();

		emailValidator = new EmailValidator();

		subContractorJobList = new ArrayList<SubContractorJob>();

		try
		{
			image = ImageIO.read(new File("img/background/background.jpg"));
		} 
		catch (IOException e)
		{
			msgError(null, "Could not load background image");
		}

		JLabel redPanelLabelTitle = new JLabel("SUBCONTRACTOR MENU");
		redPanelLabelTitle.setBounds(10, 0, 261, 28);
		redPanelLabelTitle.setForeground(Color.WHITE);
		redPanelLabelTitle.setFont(new Font("Arial Unicode MS", Font.BOLD, 20));

		statistics = new JButton();
		statistics.setLocation(684, 354);
		statistics.setSize(100, 20);
		statistics.setOpaque(false);
		statistics.setText("Statistics");
		statistics.addActionListener(this);

		btnBack = new JButton();
		btnBack.addActionListener(this);
		btnBack.setText("Back");
		btnBack.setOpaque(false);
		btnBack.setBounds(10, 354, 100, 20);

		/******************************************************
		 * 
		 * New SubContractor pane
		 * 
		 ******************************************************/

		newSubContractor = new ImagePanel(image);

		JLabel newSubContractorLabelName = new JLabel("SubContractor Name:");
		JLabel newSubContractorLabelPhoneno = new JLabel("SubContractor PhoneNo:");
		JLabel newSubContractorLabelEmail = new JLabel("SubContractor E-mail:");
		JLabel newSubContractorLabelStatus = new JLabel("SubContractor Status:");
		JLabel newSubContractorLabelCountry = new JLabel("SubContractor Country:");
		JLabel newSubContractorLabelCity = new JLabel("SubContractor City:");

		newSubContractorTextFieldUsername = new JTextField();
		newSubContractorTextFieldUsername.setColumns(10);

		newSubContractorTextFieldPhoneNo = new JTextField();
		newSubContractorTextFieldPhoneNo.setColumns(10);

		newSubContractorTextFieldEmail = new JTextField();
		newSubContractorTextFieldEmail.setColumns(10);

		newSubContractorComboBoxStatus = new JComboBox<String>();
		newSubContractorComboBoxStatus.setOpaque(false);
		newSubContractorComboBoxStatus.addItem("Active");
		newSubContractorComboBoxStatus.addItem("Inactive");

		newSubContractorComboBoxCountry = new JComboBox<String>();
		newSubContractorComboBoxCountry.setOpaque(false);
		newSubContractorComboBoxCountry.addActionListener(this);

		newSubContractorComboBoxCity = new JComboBox<String>();
		newSubContractorComboBoxCity.setOpaque(false);
		newSubContractorComboBoxCity.setEnabled(false);

		newSubContractorButtonCreateSubContractor = new JButton("Create SubContractor");
		newSubContractorButtonCreateSubContractor.setOpaque(false);
		newSubContractorButtonCreateSubContractor.addActionListener(this);
		newSubContractorButtonCreateSubContractor.setEnabled(false);

		newSubContractorTextFields = new ArrayList<JTextField>();
		newSubContractorTextFields.add(newSubContractorTextFieldUsername);
		newSubContractorTextFields.add(newSubContractorTextFieldPhoneNo);
		newSubContractorTextFields.add(newSubContractorTextFieldEmail);

		newSubContractorComboBoxJob = new JComboBox<String>();
		newSubContractorComboBoxJob.setOpaque(false);

		JLabel newSubContractorLabelJob = new JLabel("SubContractor Job:");
		GroupLayout gl_newSubContractor = new GroupLayout(newSubContractor);
		gl_newSubContractor.setHorizontalGroup(
				gl_newSubContractor.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_newSubContractor.createSequentialGroup()
						.addGap(245)
						.addGroup(gl_newSubContractor.createParallelGroup(Alignment.LEADING)
								.addComponent(newSubContractorLabelName)
								.addComponent(newSubContractorLabelPhoneno)
								.addComponent(newSubContractorLabelEmail)
								.addComponent(newSubContractorLabelJob)
								.addComponent(newSubContractorLabelStatus)
								.addComponent(newSubContractorLabelCountry)
								.addComponent(newSubContractorLabelCity))
								.addGap(40)
								.addGroup(gl_newSubContractor.createParallelGroup(Alignment.LEADING, false)
										.addComponent(newSubContractorTextFieldPhoneNo)
										.addComponent(newSubContractorTextFieldEmail)
										.addComponent(newSubContractorComboBoxJob, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(newSubContractorComboBoxCountry, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(newSubContractorComboBoxCity, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(newSubContractorButtonCreateSubContractor, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(newSubContractorTextFieldUsername)
										.addComponent(newSubContractorComboBoxStatus, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
										.addContainerGap(245, Short.MAX_VALUE))
				);
		gl_newSubContractor.setVerticalGroup(
				gl_newSubContractor.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_newSubContractor.createSequentialGroup()
						.addGap(20)
						.addGroup(gl_newSubContractor.createParallelGroup(Alignment.BASELINE)
								.addComponent(newSubContractorTextFieldUsername, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(newSubContractorLabelName))
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addGroup(gl_newSubContractor.createParallelGroup(Alignment.BASELINE)
										.addComponent(newSubContractorLabelPhoneno)
										.addComponent(newSubContractorTextFieldPhoneNo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(ComponentPlacement.UNRELATED)
										.addGroup(gl_newSubContractor.createParallelGroup(Alignment.BASELINE)
												.addComponent(newSubContractorTextFieldEmail, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addComponent(newSubContractorLabelEmail))
												.addPreferredGap(ComponentPlacement.UNRELATED)
												.addGroup(gl_newSubContractor.createParallelGroup(Alignment.BASELINE)
														.addComponent(newSubContractorComboBoxJob, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
														.addComponent(newSubContractorLabelJob))
														.addPreferredGap(ComponentPlacement.UNRELATED)
														.addGroup(gl_newSubContractor.createParallelGroup(Alignment.BASELINE)
																.addComponent(newSubContractorLabelStatus)
																.addComponent(newSubContractorComboBoxStatus, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																.addPreferredGap(ComponentPlacement.UNRELATED)
																.addGroup(gl_newSubContractor.createParallelGroup(Alignment.BASELINE)
																		.addComponent(newSubContractorComboBoxCountry, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
																		.addComponent(newSubContractorLabelCountry))
																		.addPreferredGap(ComponentPlacement.UNRELATED)
																		.addGroup(gl_newSubContractor.createParallelGroup(Alignment.BASELINE)
																				.addComponent(newSubContractorComboBoxCity, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
																				.addComponent(newSubContractorLabelCity))
																				.addGap(12)
																				.addComponent(newSubContractorButtonCreateSubContractor)
																				.addContainerGap(20, Short.MAX_VALUE))
				);
		newSubContractor.setLayout(gl_newSubContractor);

		/******************************************************
		 * 
		 * All subcontractors pane
		 * 
		 ******************************************************/

		//allSubContractors = new JPanel();

		allSubContractors = new ImagePanel(image);

		String allSubContractorsColumns [] = { "#", "Username", "Job", "PhoneNo", "Email", "City", "Country", "", "Active" };
		allSubContractorsTableModel = new DefaultTableModel(null, allSubContractorsColumns);

		allSubContractorsTable = new JTable(allSubContractorsTableModel)
		{
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex) 
			{
				return false;
			}

			public Class<?> getColumnClass(int column)   
			{   
				return getValueAt(0, column).getClass();   
			}  
		};

		Dimension dim = allSubContractorsTable.getPreferredSize(); 
		double width = dim.width / allSubContractorsColumns.length; 
		double[] width_2 = { 0.3, 1.2, 1.2, 2, 1, 1, 1, 0.5, 0.5 };

		for (int i = 0; i < allSubContractorsColumns.length; i++)
			allSubContractorsTable.getColumnModel().getColumn(i).setPreferredWidth((int) (width*width_2[i])); 

		allSubContractorsTable.setAutoCreateRowSorter(true);

		allSubContractorsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane allSubContractorsTableScroll = new JScrollPane(allSubContractorsTable);

		JLabel allSubContractorsLabelSearchBy = new JLabel("Search by:");
		JLabel allSubContractorsLabelSearchFor = new JLabel("Search for:");

		allSubContractorsComboBoxSearchType = new JComboBox<String>();
		allSubContractorsComboBoxSearchType.setOpaque(false);
		allSubContractorsComboBoxSearchType.addActionListener(this);
		allSubContractorsComboBoxSearchType.addItem("Everything");
		allSubContractorsComboBoxSearchType.addItem("Name");
		allSubContractorsComboBoxSearchType.addItem("Email");
		allSubContractorsComboBoxSearchType.addItem("PhoneNo");
		allSubContractorsComboBoxSearchType.addItem("City");
		allSubContractorsComboBoxSearchType.addItem("Country");

		allSubContractorsTextFieldSearchFor = new JTextField();
		allSubContractorsTextFieldSearchFor.getDocument().addDocumentListener(new DocumentListener()
		{
			@Override
			public void insertUpdate(DocumentEvent e)
			{
				// most likely to never be used .. 
				searchSubContractors();						
			}

			@Override
			public void changedUpdate(DocumentEvent e)
			{
				searchSubContractors();
			}

			@Override
			public void removeUpdate(DocumentEvent e)
			{
				searchSubContractors();
			}
		});

		allSubContractorsButtonSearchClear = new JButton("Clear Search");
		allSubContractorsButtonSearchClear.setOpaque(false);
		allSubContractorsButtonSearchClear.addActionListener(this);

		allSubContractorsButtonEditSubContractor = new JButton("Edit Subcontractor");
		allSubContractorsButtonEditSubContractor.setOpaque(false);
		allSubContractorsButtonEditSubContractor.addActionListener(this);

		allSubContractorsButtonDeactivateSubContractor = new JButton("Change Status");
		allSubContractorsButtonDeactivateSubContractor.setOpaque(false);
		allSubContractorsButtonDeactivateSubContractor.addActionListener(this);

		allSubContractorsCheckBoxOnlyActiveSubContractors = new JCheckBox("Only active subcontractors");
		allSubContractorsCheckBoxOnlyActiveSubContractors.setOpaque(false);
		allSubContractorsCheckBoxOnlyActiveSubContractors.setSelected(true);
		allSubContractorsCheckBoxOnlyActiveSubContractors.addActionListener(this);

		JLabel allSubContractorsLabelSearchJobs = new JLabel("Search jobs:");

		allSubContractorsComboBoxSearchJobs = new JComboBox<String>();
		allSubContractorsComboBoxSearchJobs.addActionListener(this);

		GroupLayout gl_allSubContractors = new GroupLayout(allSubContractors);
		gl_allSubContractors.setHorizontalGroup(
				gl_allSubContractors.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_allSubContractors.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_allSubContractors.createParallelGroup(Alignment.LEADING)
								.addComponent(allSubContractorsTableScroll, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 816, Short.MAX_VALUE)
								.addGroup(gl_allSubContractors.createSequentialGroup()
										.addGroup(gl_allSubContractors.createParallelGroup(Alignment.LEADING)
												.addComponent(allSubContractorsLabelSearchJobs)
												.addComponent(allSubContractorsLabelSearchBy)
												.addComponent(allSubContractorsLabelSearchFor))
												.addGap(18)
												.addGroup(gl_allSubContractors.createParallelGroup(Alignment.LEADING, false)
														.addComponent(allSubContractorsComboBoxSearchJobs, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(allSubContractorsComboBoxSearchType, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(allSubContractorsTextFieldSearchFor, GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE))
														.addGap(18)
														.addGroup(gl_allSubContractors.createParallelGroup(Alignment.LEADING)
																.addGroup(gl_allSubContractors.createSequentialGroup()
																		.addComponent(allSubContractorsButtonSearchClear)
																		.addPreferredGap(ComponentPlacement.RELATED, 236, Short.MAX_VALUE)
																		.addComponent(allSubContractorsButtonEditSubContractor)
																		.addPreferredGap(ComponentPlacement.UNRELATED)
																		.addComponent(allSubContractorsButtonDeactivateSubContractor))
																		.addComponent(allSubContractorsCheckBoxOnlyActiveSubContractors))))
																		.addContainerGap())
				);
		gl_allSubContractors.setVerticalGroup(
				gl_allSubContractors.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_allSubContractors.createSequentialGroup()
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addGroup(gl_allSubContractors.createParallelGroup(Alignment.BASELINE)
								.addComponent(allSubContractorsLabelSearchJobs)
								.addComponent(allSubContractorsComboBoxSearchJobs, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(gl_allSubContractors.createParallelGroup(Alignment.BASELINE)
										.addComponent(allSubContractorsLabelSearchBy)
										.addComponent(allSubContractorsComboBoxSearchType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
										.addComponent(allSubContractorsCheckBoxOnlyActiveSubContractors))
										.addPreferredGap(ComponentPlacement.RELATED)
										.addGroup(gl_allSubContractors.createParallelGroup(Alignment.LEADING)
												.addGroup(gl_allSubContractors.createParallelGroup(Alignment.BASELINE)
														.addComponent(allSubContractorsLabelSearchFor)
														.addComponent(allSubContractorsButtonDeactivateSubContractor)
														.addComponent(allSubContractorsButtonEditSubContractor))
														.addGroup(gl_allSubContractors.createParallelGroup(Alignment.BASELINE)
																.addComponent(allSubContractorsTextFieldSearchFor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
																.addComponent(allSubContractorsButtonSearchClear)))
																.addPreferredGap(ComponentPlacement.RELATED)
																.addComponent(allSubContractorsTableScroll, GroupLayout.PREFERRED_SIZE, 179, GroupLayout.PREFERRED_SIZE)
																.addGap(63))
				);
		allSubContractors.setLayout(gl_allSubContractors);


		jobsSubContractor = new ImagePanel(image);

		JPanel jobsSubContractorNew = new JPanel();
		jobsSubContractorNew.setOpaque(false);
		jobsSubContractorNew.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "New Subcontractor Job", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));

		JPanel jobsSubContractorEdit = new JPanel();
		jobsSubContractorEdit.setBorder(new TitledBorder(null, "Edit Subcontractor Job", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		jobsSubContractorEdit.setOpaque(false);
		GroupLayout gl_jobsSubContractor = new GroupLayout(jobsSubContractor);
		gl_jobsSubContractor.setHorizontalGroup(
				gl_jobsSubContractor.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_jobsSubContractor.createSequentialGroup()
						.addGap(14)
						.addComponent(jobsSubContractorNew, GroupLayout.PREFERRED_SIZE, 268, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(jobsSubContractorEdit, GroupLayout.PREFERRED_SIZE, 465, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(36, Short.MAX_VALUE))
				);
		gl_jobsSubContractor.setVerticalGroup(
				gl_jobsSubContractor.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_jobsSubContractor.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_jobsSubContractor.createParallelGroup(Alignment.BASELINE)
								.addComponent(jobsSubContractorEdit, GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
								.addComponent(jobsSubContractorNew, GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE))
								.addContainerGap())
				);

		jobsSubContractorEditListJobsModel = new DefaultListModel<String>();
		jobsSubContractorEditListJobs = new JList<String>(jobsSubContractorEditListJobsModel);

		jobsSubContractorEditListScrollPane = new JScrollPane();
		jobsSubContractorEditListScrollPane.setOpaque(false);
		jobsSubContractorEditListScrollPane.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Current Jobs", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		jobsSubContractorEditListScrollPane.setViewportView(jobsSubContractorEditListJobs);

		jobsSubContractorEditListJobs.setOpaque(false);
		jobsSubContractorEditListJobs.setBorder(null);
		jobsSubContractorEditListJobs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		jobsSubContractorEditListJobs.setSelectedIndex(0);
		jobsSubContractorEditListJobs.setVisibleRowCount(4);
		jobsSubContractorEditListJobs.addListSelectionListener(this);

		JLabel jobsSubContractorEditLabelJobName = new JLabel("Job Name:");
		JLabel jobsSubContractorEditLabelJobCount = new JLabel("Job Count:");

		jobsSubContractorEditTextFieldJobName = new JTextField();

		jobsSubContractorEditTextFieldJobCount = new JTextField();
		jobsSubContractorEditTextFieldJobCount.setEditable(false);
		jobsSubContractorEditTextFieldJobCount.setEnabled(false);

		jobsSubContractorEditButtonJobEdit = new JButton("Edit job");
		jobsSubContractorEditButtonJobEdit.addActionListener(this);

		jobsSubContractorEditButtonJobEdit.setOpaque(false);
		GroupLayout gl_jobsSubContractorEdit = new GroupLayout(jobsSubContractorEdit);
		gl_jobsSubContractorEdit.setHorizontalGroup(
				gl_jobsSubContractorEdit.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_jobsSubContractorEdit.createSequentialGroup()
						.addGroup(gl_jobsSubContractorEdit.createParallelGroup(Alignment.TRAILING)
								.addGroup(gl_jobsSubContractorEdit.createSequentialGroup()
										.addGap(22)
										.addGroup(gl_jobsSubContractorEdit.createParallelGroup(Alignment.LEADING)
												.addComponent(jobsSubContractorEditLabelJobName)
												.addComponent(jobsSubContractorEditLabelJobCount))
												.addGap(27)
												.addGroup(gl_jobsSubContractorEdit.createParallelGroup(Alignment.LEADING, false)
														.addComponent(jobsSubContractorEditTextFieldJobCount)
														.addComponent(jobsSubContractorEditTextFieldJobName, GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)))
														.addGroup(gl_jobsSubContractorEdit.createSequentialGroup()
																.addContainerGap()
																.addComponent(jobsSubContractorEditButtonJobEdit)
																.addGap(28)))
																.addGap(82)
																.addComponent(jobsSubContractorEditListScrollPane, GroupLayout.PREFERRED_SIZE, 142, GroupLayout.PREFERRED_SIZE)
																.addContainerGap())
				);
		gl_jobsSubContractorEdit.setVerticalGroup(
				gl_jobsSubContractorEdit.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_jobsSubContractorEdit.createSequentialGroup()
						.addGroup(gl_jobsSubContractorEdit.createParallelGroup(Alignment.LEADING)
								.addComponent(jobsSubContractorEditListScrollPane, GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
								.addGroup(gl_jobsSubContractorEdit.createSequentialGroup()
										.addGap(56)
										.addGroup(gl_jobsSubContractorEdit.createParallelGroup(Alignment.BASELINE)
												.addComponent(jobsSubContractorEditTextFieldJobName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addComponent(jobsSubContractorEditLabelJobName))
												.addPreferredGap(ComponentPlacement.RELATED)
												.addGroup(gl_jobsSubContractorEdit.createParallelGroup(Alignment.BASELINE)
														.addComponent(jobsSubContractorEditLabelJobCount)
														.addComponent(jobsSubContractorEditTextFieldJobCount, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
														.addGap(26)
														.addComponent(jobsSubContractorEditButtonJobEdit)))
														.addContainerGap())
				);
		jobsSubContractorEdit.setLayout(gl_jobsSubContractorEdit);

		JLabel jobsSubContractorNewLabelJobName = new JLabel("Job Name:");

		jobsSubContractorNewTextFieldJobName = new JTextField();

		jobsSubContractorNewButtonJobAdd = new JButton("Add job");
		jobsSubContractorNewButtonJobAdd.addActionListener(this);

		jobsSubContractorNewButtonJobAdd.setOpaque(false);
		GroupLayout gl_jobsSubContractorNew = new GroupLayout(jobsSubContractorNew);
		gl_jobsSubContractorNew.setHorizontalGroup(
				gl_jobsSubContractorNew.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_jobsSubContractorNew.createSequentialGroup()
						.addContainerGap(27, Short.MAX_VALUE)
						.addGroup(gl_jobsSubContractorNew.createParallelGroup(Alignment.LEADING)
								.addGroup(Alignment.TRAILING, gl_jobsSubContractorNew.createSequentialGroup()
										.addComponent(jobsSubContractorNewLabelJobName)
										.addGap(18)
										.addComponent(jobsSubContractorNewTextFieldJobName, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE)
										.addGap(50))
										.addGroup(Alignment.TRAILING, gl_jobsSubContractorNew.createSequentialGroup()
												.addComponent(jobsSubContractorNewButtonJobAdd)
												.addGap(71))))
				);
		gl_jobsSubContractorNew.setVerticalGroup(
				gl_jobsSubContractorNew.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_jobsSubContractorNew.createSequentialGroup()
						.addGap(57)
						.addGroup(gl_jobsSubContractorNew.createParallelGroup(Alignment.BASELINE)
								.addComponent(jobsSubContractorNewLabelJobName)
								.addComponent(jobsSubContractorNewTextFieldJobName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addGap(51)
								.addComponent(jobsSubContractorNewButtonJobAdd)
								.addContainerGap(85, Short.MAX_VALUE))
				);
		jobsSubContractorNew.setLayout(gl_jobsSubContractorNew);
		jobsSubContractor.setLayout(gl_jobsSubContractor);


		try
		{
			searchSubContractors();
			redPanel.setLayout(null);
			updateCountries(newSubContractorComboBoxCountry, true);
			redPanel.add(tabbedPane);
			redPanel.add(redPanelLabelTitle);
			redPanel.add(btnBack);
			redPanel.add(statistics);

			btnPrint = new JButton();
			btnPrint.addActionListener(this);
			btnPrint.setText("Print");
			btnPrint.setOpaque(false);
			btnPrint.setBounds(574, 353, 100, 20);
			redPanel.add(btnPrint);
			updateJobs();
		}
		catch (Exception e)
		{
			msgError(allSubContractors, "Could not load properly");
		}
	}

	/**
	 * ActionPerformed.. where all the magic happens.
	 * Our listener for every action which happens.
	 * 
	 * @param 	e	the event which has triggered the listener
	 * 
	 * @return 	void 
	 */
	@Override
	public void actionPerformed(ActionEvent e)
	{
		frameSubContractorUI.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

		if (e.getSource() == allSubContractorsCheckBoxOnlyActiveSubContractors)
		{
			searchSubContractors();
		}
		else if (e.getSource() == allSubContractorsButtonSearchClear)
		{
			allSubContractorsComboBoxSearchType.setSelectedIndex(0);
			allSubContractorsComboBoxSearchJobs.setSelectedIndex(0);
			allSubContractorsTextFieldSearchFor.setText(null);
		}
		else if ((e.getSource() == allSubContractorsComboBoxSearchType) || (e.getSource() == allSubContractorsComboBoxSearchJobs))
		{
			if (startup)
			{
				allSubContractorsTextFieldSearchFor.setText(null);

				searchSubContractors();
			}
		}
		else if(e.getSource() == statistics)
		{
			StatisticsUI stats = StatisticsUI.getInstance();
			stats.display();
			frameSubContractorUI.setVisible(false);
		}
		else if (e.getSource() == allSubContractorsButtonEditSubContractor)
		{
			showEditSubContractorDialog();
		}
		else if (e.getSource() == newSubContractorComboBoxCountry) 
		{
			updateCities((newSubContractorComboBoxCountry.getSelectedIndex() > 0), newSubContractorComboBoxCity, newSubContractorComboBoxCountry);
		}
		else if (e.getSource() == editSubContractorComboBoxCountry)
		{
			updateCities(true, editSubContractorComboBoxCity, editSubContractorComboBoxCountry);
		}
		else if (e.getSource() == newSubContractorButtonCreateSubContractor)
		{
			addSubContractor();
		}
		else if (e.getSource() == allSubContractorsButtonDeactivateSubContractor)
		{
			activateSubContractor();
		}
		else if (e.getSource() == jobsSubContractorNewButtonJobAdd)
		{
			addSubContractorJob();
		}
		else if (e.getSource() == jobsSubContractorEditButtonJobEdit)
		{
			editSubContractorJob();
		}
		else if(e.getSource() == btnBack)
		{
			back.goBack(back.getNumber());
		}
		else if (e.getSource() == btnPrint)
		{
			printSubContractorPDF();
		}
		
		frameSubContractorUI.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	}

	private void printSubContractorPDF()
	{
		if (allSubContractorsTable.getRowCount() > 0)
		{
			ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

			String columns [] = { "#", "Username", "Job", "PhoneNo", "Email", "City", "Country", "Active" };

			ArrayList<String> subContractorID = new ArrayList<String>();
			ArrayList<String> subContractorJob = new ArrayList<String>();
			ArrayList<String> subContractorUsername = new ArrayList<String>();
			ArrayList<String> subContractorPhoneNo = new ArrayList<String>();
			ArrayList<String> subContractorEmail = new ArrayList<String>();
			ArrayList<String> subContractorCity = new ArrayList<String>();
			ArrayList<String> subContractorCountry = new ArrayList<String>();
			ArrayList<String> subContractorActive = new ArrayList<String>();

			list.add(subContractorID);
			list.add(subContractorJob);
			list.add(subContractorUsername);
			list.add(subContractorPhoneNo);
			list.add(subContractorEmail);
			list.add(subContractorCity);
			list.add(subContractorCountry);
			list.add(subContractorActive);

			for(int i = 0; i < allSubContractorsTable.getRowCount(); i++)
			{
				list.get(0).add(String.valueOf(allSubContractorsTable.getValueAt(i, 0)));
				list.get(1).add(String.valueOf(allSubContractorsTable.getValueAt(i, 1)));
				list.get(2).add(String.valueOf(allSubContractorsTable.getValueAt(i, 2)));
				list.get(3).add(String.valueOf(allSubContractorsTable.getValueAt(i, 3)));
				list.get(4).add(String.valueOf(allSubContractorsTable.getValueAt(i, 4)));
				list.get(5).add(String.valueOf(allSubContractorsTable.getValueAt(i, 5)));
				list.get(6).add(String.valueOf(allSubContractorsTable.getValueAt(i, 6)));
				list.get(7).add(String.valueOf(allSubContractorsTable.getValueAt(i, 8)).contains("yes") ? "Yes" : "No");
			}

			PdfFilePrint pdfPrint = new PdfFilePrint();
			boolean successPDF = pdfPrint.PDFPrint("SubContractor", "Current SubContractors", "subcontractor", "Nikola", columns, list);

			if(successPDF)
				msgSuccess(null, "PDF was created successfully");
			else
				msgError(null, "There was an error creating the PDF");
		}
		else
		{
			msgError(null, "Nothing to print");
		}
	}

	@Override
	public void valueChanged(ListSelectionEvent e)
	{
		if (e.getSource() == jobsSubContractorEditListJobs)
		{
			if (!e.getValueIsAdjusting())
			{
				try
				{
					SubContractorJob selectedJob = subContractorCtrl.findSubContractorJobByName(jobsSubContractorEditListJobs.getSelectedValue());
					int selectedJobCount = subContractorCtrl.findSubcontractorJobCount(selectedJob.getJobID());

					jobsSubContractorEditTextFieldJobName.setText(selectedJob.getJobName());
					jobsSubContractorEditTextFieldJobCount.setText(String.valueOf(selectedJobCount));
				}
				catch (SQLException ex)
				{
					ex.printStackTrace();
				}        	
			}
		}
	}

	/**
	 * Populates the job list
	 * 
	 * @return		void
	 */
	private void updateJobList()
	{
		jobsSubContractorEditListJobsModel.removeAllElements();

		for (SubContractorJob jobs : subContractorJobList)
		{
			jobsSubContractorEditListJobsModel.addElement(jobs.getJobName());	
		}		
	}

	/**
	 * Necessary checks when adding a subcontractor job
	 * 
	 * @return		void
	 */
	private void addSubContractorJob()
	{
		if ((jobsSubContractorNewTextFieldJobName.getText().trim().length() > 0) || (jobsSubContractorNewTextFieldJobName.getText().length() > 100)) 
		{
			try
			{
				int success = subContractorCtrl.createSubContractorJob(jobsSubContractorNewTextFieldJobName.getText());

				if (success > 0)
				{
					updateJobs();
					msgSuccess(jobsSubContractor, "Job \"" + jobsSubContractorNewTextFieldJobName.getText() + "\" was added successfully");

					jobsSubContractorNewTextFieldJobName.setText(null);
				}
				else 
				{
					msgError(jobsSubContractor, "There is already job with the same name");					
				}
			}
			catch (SQLException e)
			{
				msgError(jobsSubContractor, "There was a problem while adding the job");
			}
		}
		else 
		{
			msgError(jobsSubContractor, "You have not written a job name or it is over 100 symbols");
		}
	}

	/**
	 * Necessary checks when editing a subcontractor job
	 * 
	 * @return		void
	 */
	private void editSubContractorJob()
	{
		if (!jobsSubContractorEditListJobs.isSelectionEmpty())
		{
			if ((jobsSubContractorEditTextFieldJobName.getText().trim().length() > 0) || (jobsSubContractorEditTextFieldJobName.getText().length() > 100)) 
			{
				try
				{
					SubContractorJob selectedJob = subContractorCtrl.findSubContractorJobByName(jobsSubContractorEditListJobs.getSelectedValue());

					int success = subContractorCtrl.updateSubContractorJob(selectedJob.getJobID(), jobsSubContractorEditTextFieldJobName.getText());

					if (success > 0)
					{
						msgSuccess(jobsSubContractor, "Job \"" + selectedJob.getJobName() + "\" is successfully edited and is now known as \"" + jobsSubContractorEditTextFieldJobName.getText() + "\"");
						updateJobs();

						jobsSubContractorEditTextFieldJobName.setText(null);
					}
					else 
					{
						msgError(jobsSubContractor, "There is already job with the same name");					
					}
				}
				catch (SQLException e)
				{
					msgError(jobsSubContractor, "There was a problem while adding the job");
				}
			}
			else 
			{
				msgError(jobsSubContractor, "You have not written a job name or it is over 100 symbols");
			}
		}
		else 
		{
			msgError(jobsSubContractor, "You have not selected a job");			
		}
	}

	/**
	 * Necessary checks when adding a subcontractor
	 * 
	 * @return		void
	 */
	private void addSubContractor()
	{
		boolean validInfo = subContractorCheckValidInfo(newSubContractorTextFields);
		boolean validEmail = emailValidator.validate(newSubContractorTextFieldEmail.getText());

		if (validInfo && validEmail)
		{
			try
			{
				int success = outsiderCtrl.createOutsider(newSubContractorTextFieldUsername.getText(), newSubContractorTextFieldPhoneNo.getText(), cityCtrl.getOneCity("name",newSubContractorComboBoxCity.getSelectedItem().toString(), newSubContractorComboBoxCountry.getSelectedItem().toString()), (newSubContractorComboBoxStatus.getSelectedIndex() == 0), newSubContractorTextFieldEmail.getText(), subContractorCtrl.findSubContractorJobByName(newSubContractorComboBoxJob.getSelectedItem().toString()).getJobID());

				if (success > 0)
				{
					msgSuccess(newSubContractor, "SubContractor \"" + newSubContractorTextFieldUsername.getText() + "\" has been added successfully");

					for(JTextField tf : newSubContractorTextFields)
						tf.setText(null);

					searchSubContractors();
					updateCountries(newSubContractorComboBoxCountry, true);
				}
				else
				{
					msgError(newSubContractor, "There was an error adding the subcontractor.\nThis username already exists in the system.");					
				}
			}
			catch (Exception ex)
			{
				msgError(newSubContractor, "There was an error adding the subcontractor.\nThis username already exists in the system.");
			}
		}
		else 
		{
			String error = "You cannot proceed due some errors:\n\n";

			if (!validInfo)
				error += " - You haven't filled up every text area or a field exceeds 32 symbols\n";

			if (!validEmail)
				error += " - Email is not valid\n";

			msgError(newSubContractor, error);
		}		
	}

	/**
	 * Necessary checks (and dialog opening) when editing a sub contractor
	 * 
	 * @return		void
	 */
	private void showEditSubContractorDialog()
	{
		if (allSubContractorsTable.getSelectedRow() > -1) 
		{
			try
			{
				int subContractorID = Integer.valueOf(String.valueOf(allSubContractorsTable.getValueAt(allSubContractorsTable.getSelectedRow(), 0)));

				SubContractor editSubContractor = subContractorCtrl.searchSubContractorID(subContractorID);

				JPanel panel = new JPanel(new GridLayout(0, 2, 5, 5));

				JTextField editSubContractorTextFieldsubContractorName = new JTextField(editSubContractor.getName());
				JTextField editSubContractorTextFieldsubContractorPhoneNo = new JTextField(editSubContractor.getPhoneNo());
				JTextField editSubContractorTextFieldsubContractorEmail = new JTextField(editSubContractor.getEmail());

				JComboBox<String> editSubContractorComboBoxActive = new JComboBox<String>();
				editSubContractorComboBoxActive.addItem("Active");
				editSubContractorComboBoxActive.addItem("Inactive");
				editSubContractorComboBoxActive.setSelectedIndex(editSubContractor.isActive() ? 0 : 1);

				editSubContractorComboBoxCountry = new JComboBox<String>();
				updateCountries(editSubContractorComboBoxCountry, false);
				editSubContractorComboBoxCountry.setSelectedItem(editSubContractor.getCity().getCountry().getName());
				editSubContractorComboBoxCountry.addActionListener(this);

				editSubContractorComboBoxCity = new JComboBox<String>();
				updateCities(true, editSubContractorComboBoxCity, editSubContractorComboBoxCountry);
				editSubContractorComboBoxCity.setSelectedItem(editSubContractor.getCity().getName());

				editSubContractorComboBoxJob = new JComboBox<String>();
				updateJobComboBox(editSubContractorComboBoxJob, false);
				editSubContractorComboBoxJob.setSelectedItem(editSubContractor.getJob().getJobName());			

				panel.add(new JLabel("SubContractor Name:"));
				panel.add(editSubContractorTextFieldsubContractorName);
				panel.add(new JLabel("SubContractor PhoneNo:"));
				panel.add(editSubContractorTextFieldsubContractorPhoneNo);
				panel.add(new JLabel("SubContractor E-mail:"));
				panel.add(editSubContractorTextFieldsubContractorEmail);
				panel.add(new JLabel("SubContractor Status:"));
				panel.add(editSubContractorComboBoxActive);
				panel.add(new JLabel("SubContractor Job:"));
				panel.add(editSubContractorComboBoxJob);
				panel.add(new JLabel("SubContractor Country:"));
				panel.add(editSubContractorComboBoxCountry);
				panel.add(new JLabel("SubContractor City:"));
				panel.add(editSubContractorComboBoxCity);

				editSubContractorTextFields = new ArrayList<JTextField>();
				editSubContractorTextFields.add(editSubContractorTextFieldsubContractorName);
				editSubContractorTextFields.add(editSubContractorTextFieldsubContractorPhoneNo);
				editSubContractorTextFields.add(editSubContractorTextFieldsubContractorEmail);

				int option = JOptionPane.showConfirmDialog(allSubContractors, panel, "Edit SubContractor", JOptionPane.OK_CANCEL_OPTION);

				if (option == JOptionPane.YES_OPTION)
				{
					boolean validInfo = subContractorCheckValidInfo(editSubContractorTextFields);
					boolean validEmail = emailValidator.validate(editSubContractorTextFieldsubContractorEmail.getText());

					if (validInfo && validEmail)
					{
						int success = outsiderCtrl.updateOutsider(subContractorID, editSubContractorTextFieldsubContractorName.getText(), editSubContractorTextFieldsubContractorPhoneNo.getText(), cityCtrl.getOneCity("name",editSubContractorComboBoxCity.getSelectedItem().toString(), editSubContractorComboBoxCountry.getSelectedItem().toString()), (editSubContractorComboBoxActive.getSelectedIndex() == 0), editSubContractorTextFieldsubContractorEmail.getText(), subContractorCtrl.findSubContractorJobByName(editSubContractorComboBoxJob.getSelectedItem().toString()).getJobID());

						if (success > 0)
						{
							msgSuccess(newSubContractor, "SubContractor #" + subContractorID + " has been edited successfully");
							searchSubContractors();
						}
						else 
						{
							msgError(newSubContractor, "There was an error editing the subcontractor");
						}
					}
					else 
					{
						String error = "You cannot proceed due some errors:\n\n";

						if (!validInfo)
							error += " - You haven't filled up every text area\n";

						if (!validEmail)
							error += " - Email is not valid\n";

						msgError(newSubContractor, error);
					}
				}
			}
			catch (SQLException ex)
			{
				msgError(allSubContractors, "There was a problem loading the subcontractor");
			}
		}
		else 
		{
			msgError(allSubContractors, "You have not selected a subcontractor");
		}
	}

	/**
	 * Returns if the two ArrayLists which are given are not empty
	 *
	 * @param  textFields  		an array list with all the text fields which need to be checked
	 * 
	 * @return	true			if they are not empty
	 */
	private boolean subContractorCheckValidInfo(ArrayList<JTextField> textFields)
	{
		for(JTextField tf : textFields)
		{
			if ((tf.getText().trim().length() == 0) || (tf.getText().trim().length() > 32))
				return false;
		}

		return true;
	}

	/**
	 * Updates a certain JComboBox by adding all the cities from a certain
	 * selected country on another JComboBox
	 *
	 * @param  	notEmpty			should the city combo box be empty or not
	 * @param  	cityComboBox 		the combo box which will be updated after calling this method
	 * @param	countryComboBox		the combo box from which we get the selected city in order to show only cities from this country
	 *
	 * @return	void
	 */
	private void updateCities(boolean notEmpty, JComboBox<String> cityComboBox, JComboBox<String> countryComboBox)
	{
		cityComboBox.removeAllItems();
		cityComboBox.setEnabled(notEmpty);
		newSubContractorButtonCreateSubContractor.setEnabled(notEmpty);

		if (notEmpty)
		{
			ArrayList<City> cityList = null;

			try
			{
				cityList = cityCtrl.getCitiesByCountryName(countryComboBox.getSelectedItem().toString());

				for(City city : cityList)
				{
					cityComboBox.addItem(city.getName());
				}
			}
			catch(Exception e)
			{
				msgError(newSubContractor, "Could not load cities or this country has no cities set");
			}
		}
	}

	/**
	 * Updates a certain JComboBox by adding all the countries
	 *
	 * @param  	comboBox 		the combo box which will be updated after calling this method
	 * @param	emptyField		should the combo box have one empty field on top
	 * 
	 * @return	void
	 */
	private void updateCountries(JComboBox<String> comboBox, boolean emptyField)
	{
		comboBox.removeAllItems();

		if (emptyField)
			comboBox.addItem(null);

		ArrayList<Country> countryList = null;

		try
		{
			countryList = countryCtrl.getAllCountries();

			for(Country country : countryList)
				comboBox.addItem(country.getName());
		}
		catch(Exception e)
		{
			msgError(newSubContractor, "Could not load countries");
		}
	}

	private void updateJobs()
	{
		try
		{
			subContractorJobList = subContractorCtrl.printAllSubContractorJobs();

			updateJobComboBox(allSubContractorsComboBoxSearchJobs, true);
			updateJobComboBox(newSubContractorComboBoxJob, false);
			updateJobList();
		}
		catch(Exception e)
		{
			msgError(newSubContractor, "Could not load jobs");
		}
	}

	/**
	 * Updates selected combo box with all the subcontractor jobs
	 * 
	 * @param comboBox		which combo box should it update
	 * @param emptyField	should it add a fake/empty first row
	 * 
	 * @return void
	 */
	private void updateJobComboBox(JComboBox<String> comboBox, boolean emptyField)
	{
		comboBox.removeAllItems();

		if (emptyField)
			comboBox.addItem("All jobs");

		try
		{
			for(SubContractorJob job : subContractorJobList)
				comboBox.addItem(job.getJobName());
		}
		catch(Exception e)
		{
			msgError(newSubContractor, "Could not load jobs");
		}
	}

	/**
	 * Updating the all subcontractor table
	 *
	 * @param  	subContractorList 	the array list which is put in the table
	 * 
	 * @return	void
	 */
	private void allSubContractorsUpdateTable(ArrayList<SubContractor> subContractorList)
	{
		if (subContractorList.size() > 0)
		{
			tableClearList();

			for(SubContractor subContractor : subContractorList)
			{
				allSubContractorsTableModel.addRow(
						new Object[]
								{ 
								subContractor.getOutsiderID(), 
								subContractor.getName(),
								subContractor.getJob().getJobName(),
								subContractor.getPhoneNo(),
								subContractor.getEmail(),
								subContractor.getCity().getName(),
								subContractor.getCity().getCountry().getName(),
								new ImageIcon("img/flags/" + subContractor.getCity().getCountry().getTld() + ".png"),
								new ImageIcon("img/tick_" + (subContractor.isActive() ? "yes" : "no") + ".png")
								} 
						);
			}
		}
	}

	/**
	 * Removing all rows from the all subcontractor table
	 *
	 * @return	void
	 */
	private void tableClearList()
	{
		DefaultTableModel dm = (DefaultTableModel) allSubContractorsTable.getModel();

		while(dm.getRowCount() > 0)
			dm.removeRow(0);
	}

	/**
	 * Activating/deactivating a subcontractor
	 *
	 * @return	void
	 */
	public void activateSubContractor()
	{
		DefaultTableModel model = (DefaultTableModel) allSubContractorsTable.getModel();
		int[] rows = allSubContractorsTable.getSelectedRows();

		for (int i = 0; i < rows.length; i++)
		{
			int subContractorID = Integer.valueOf((String.valueOf(model.getValueAt(rows[i]-i,0))));

			try
			{
				if (outsiderCtrl.activateOutsider(subContractorID) > 0)
				{
					msgSuccess(allSubContractors, "Successfully changed " + String.valueOf(model.getValueAt(rows[i]-i,1)) + "'s status");

					searchSubContractors();
				}
			}
			catch (SQLException e)
			{
				msgError(allSubContractors, "There was an error changing subcontractor " + String.valueOf(model.getValueAt(rows[i]-i,1)) + "'s status");
			}
		}
	}

	/**
	 * Searching subcontractor based on the selected drop down criteria 
	 * and input text field
	 * 
	 * @return	void
	 */
	private void searchSubContractors()
	{
		ArrayList<SubContractor> subContractorList = new ArrayList<SubContractor>();

		boolean active = allSubContractorsCheckBoxOnlyActiveSubContractors.isSelected();

		String clause = allSubContractorsComboBoxSearchType.getSelectedItem().toString().toLowerCase();
		String search = allSubContractorsTextFieldSearchFor.getText();
		String jobName = allSubContractorsComboBoxSearchJobs.getItemCount() > 0 ? (allSubContractorsComboBoxSearchJobs.getSelectedIndex() == 0 ? "" : allSubContractorsComboBoxSearchJobs.getSelectedItem().toString()) : "";

		try
		{
			switch (clause)
			{
				case "everything": 	subContractorList = subContractorCtrl.searchSubContractorEverything(active, jobName, search); break;
				case "name":		subContractorList = subContractorCtrl.searchSubContractorName(active, jobName, search); break;
				case "email":		subContractorList = subContractorCtrl.searchSubContractorEmail(active, jobName, search); break;
				case "phoneno":		subContractorList = subContractorCtrl.searchSubContractorPhoneNo(active, jobName, search); break;
				case "city":		subContractorList = subContractorCtrl.searchSubContractorCity(active, jobName, search); break;
				case "country":		subContractorList = subContractorCtrl.searchSubContractorCountry(active, jobName, search); break;
			}

			if (subContractorList.size() > 0)
				allSubContractorsUpdateTable(subContractorList);
			else
				tableClearList();
		}
		catch (Exception e)
		{
			msgError(allSubContractors, "Could not load subcontractors");
			e.printStackTrace();
		}

		if (!startup)
			startup = true;
	}

	/**
	 * Shows an error message pop-up
	 * 
	 * @param	panel 		on which panel should it show the message
	 * @param	error		the error which is printed on the pop-up window
	 * 
	 * @return	void
	 */
	private void msgError(JPanel panel, String error)
	{
		JOptionPane.showConfirmDialog(panel, error, "Error", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * Shows a success message pop-up
	 * 
	 * @param	panel 		on which panel should it show the message
	 * @param	success		the success message which is printed on the pop-up window
	 * 
	 * @return	void
	 */
	private void msgSuccess(JPanel panel, String success)
	{
		JOptionPane.showMessageDialog(panel, success, "Success", 1);
	}

	public static SubContractorUI getInstance()
	{
		if(instance == null)
			instance = new SubContractorUI();

		return instance;			
	}

	public static void main(String[] args)
	{
		try 
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 

			SubContractorUI subContractorMenu = new SubContractorUI();
			subContractorMenu.display();
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "SubContractor Menu could not load");
		}
	}
}